from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import os

app = Flask(__name__)
CORS(app, origins=['http://localhost:8000', 'http://127.0.0.1:8000'], supports_credentials=True)

# 数据库路径
DB_PATH = os.path.join('manage1', 'manage', 'db.sqlite3')

@app.route('/api/auth/register/', methods=['POST'])
def register():
    try:
        # 获取请求数据
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        user_type = data.get('userType')
        
        # 验证必填字段
        if not all([username, password, user_type]):
            return jsonify({'success': False, 'error': '请填写所有必填字段'}), 400
        
        # 验证用户类型
        if user_type not in ['resident', 'employee']:
            return jsonify({'success': False, 'error': '不支持的用户类型'}), 400
        
        # 连接数据库
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        
        # 检查用户名是否已存在
        cursor.execute("SELECT * FROM property_user WHERE username = ?", (username,))
        if cursor.fetchone():
            conn.close()
            return jsonify({'success': False, 'error': '用户名已存在'}), 400
        
        # 将英文用户类型转换为中文
        user_type_map = {
            'resident': '普通用户',
            'employee': 'employee'
        }
        db_user_type = user_type_map[user_type]
        
        # 插入新用户
        cursor.execute(
            "INSERT INTO property_user (username, password, user_type, status) VALUES (?, ?, ?, ?)",
            (username, password, db_user_type, 'active')
        )
        conn.commit()
        
        # 获取新用户ID
        user_id = cursor.lastrowid
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'user': {
                'id': user_id,
                'username': username,
                'userType': user_type
            }
        })
        
    except Exception as e:
        print(f"注册错误: {str(e)}")
        return jsonify({'success': False, 'error': '注册失败，请稍后重试'}), 500

@app.route('/api/auth/login/', methods=['POST'])
def login():
    try:
        # 获取请求数据
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        user_type = data.get('userType')
        
        # 连接数据库
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        
        # 查询用户
        cursor.execute("SELECT * FROM property_user WHERE username = ?", (username,))
        user = cursor.fetchone()
        conn.close()
        
        # 用户类型映射
        user_type_map = {
            'admin': '管理员',
            'resident': '普通用户',
            'employee': 'employee'
        }
        
        # 验证用户
        if user and user[3] == password:  # 假设密码在第4列
            # 验证用户类型
            if user[2] == user_type_map.get(user_type):  # 假设user_type在第3列
                return jsonify({
                    'success': True,
                    'user': {
                        'id': user[0],
                        'username': user[1],
                        'userType': user_type
                    }
                })
            else:
                return jsonify({'success': False, 'message': '用户类型不匹配'}), 401
        
        return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
        
    except Exception as e:
        print(f"登录错误: {str(e)}")
        return jsonify({'success': False, 'message': '登录失败'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)